package com.roc.web.action.agent;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.dao.DaoException;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.TblMerAgentRelation;
import com.roc.service.IExcelService;
import com.roc.service.IPagenitionService;
import com.roc.service.ServiceException;
import com.roc.service.agent.IAgncyService;
import com.roc.service.operator.IPowerInfoService;
import com.roc.util.Constance;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;
@Component
@Namespace("/agency")
@SuppressWarnings("serial")
@Scope(BeanDefinition.SCOPE_PROTOTYPE)

public class AgencyAction   extends PaginationBaseAction{
	
	private Logger logger = LogManager.getLogger(AgencyAction.class);
	private AgencyActionSearchCondition searchCondition;
	
	private File file;
	
	private InputStream excelFile;
	
	private String  excelName;
	
    @Autowired
	private IAgncyService agncyService;
    @Autowired
    private IPagenitionService pagenitionService;
    
    @Autowired
    private IExcelService excelService;
    
    @Autowired
    private  IPowerInfoService iPowerInfoService;
    
    /**
	 * 代理商导出初始化
	 * @return
	 */
    @Action(value = "init", results = { @Result(name = "success", location = "/pages/merinfo/agencyTransmit.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })	
	public String init() throws Exception{
		Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if(op.getRoleType().equals(Role.AGENT.getCode())&&!"sdsyb".equals(op.getAccountNo())) {
			addActionError("当前登录账号无权限访问!!!");
			return ERROR;
		}
			return SUCCESS;  
    }
   
	
	/**
	 * 批量导入商户号
	 * @Title: addBlackLists
	 * @Description: TODO
	 * @param @return    
	 * @return String    
	 * @throws
	 */
	@Action(value = "importMidList", interceptorRefs = {
			@InterceptorRef(value = "token"),
			@InterceptorRef(value = "rocDefaultStack", params = {
					"fileUpload.allowedExtensions", "xlsx",
					"fileUpload.maximumSize", "100000000" }) }, results = {
			@Result(name = "success",location = "/pages/merinfo/agencyTransmit.jsp"),
			@Result(name = "error", location = "/error.jsp"),
			@Result(name = "invalid.token", location = "/error.jsp")})
	public String importMidList()
	{
		Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if (searchCondition == null) {
			searchCondition = (AgencyActionSearchCondition) getSearchConditionFromSession();
			if (searchCondition == null) {
				searchCondition = new AgencyActionSearchCondition();
			}
		}
		
		if(op.getRoleType().equals(Role.AGENT.getCode())&&!"sdsyb".equals(op.getAccountNo())) {
			addActionError("当前登录账号无权限访问!!!");
			return ERROR;
		}
		try {
			Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
			Map<String, String> map=iPowerInfoService.queryRealIdByOpId(op.getSuperiorId(), op.getRoleType(), op.getId(), op.getOrgCode());
            String orgCode=map.get("orgCode");
            String superRole= map.get("superRole");
            String opRealId =map.get("opRealId");
            searchCondition.setOrgCode(orgCode);//当前查询人员所属机构
            searchCondition.setRoleId(superRole);// 角色
            searchCondition.setOneOrgCode(op.getOneagentid());//机构
            searchCondition.setOpId(opRealId);//当前人员id
			 resultMap=agncyService.importMidList(file, op,searchCondition);
			 if(resultMap.size()>0){
				 getRequest().getSession().setAttribute("upload_mid_map", resultMap);	
				 addActionMessage((String) resultMap.get("result"));
			 }
		} catch (Exception e) {
			e.printStackTrace();
			addActionError("批量导入商户号失败~");
		} 
		return SUCCESS;		
	}
	
	
    /**
     * @param clearList 
     * 导出excel
     * @Title: clearExcel
     * @Description: TODO
     * @param @return    
     * @return String    
     * @throws
     */
	@SuppressWarnings("unchecked")
	@Action(value="exportAgencyExcel",results = {@Result(name="success",type="stream"
			,params = { "contentType", "application/vnd.ms-excel", "inputName",  
			            "excelFile","contentDisposition",  "attachment;filename=${excelName}.xls",
 "bufferSize", "1024*3" }),@Result(name="error",location="/pages/merinfo/agencyTransmit.jsp") }) 
	public String exportAgencyExcel(){
		try{
		Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
		resultMap=(LinkedHashMap<String, Object>) getRequest().getSession().getAttribute("upload_mid_map");
		if(resultMap==null){
			addActionError("请先导入商户号！！"); 
			return SUCCESS;
		}else{
		HSSFWorkbook work = excelService.exportAgencyExcel(resultMap);
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		work.write(output);

		byte[] ba = output.toByteArray();
		excelFile = new ByteArrayInputStream(ba);
		output.flush();
		output.close();
		getRequest().getSession().setAttribute("upload_mid_map", ""); 
			}
	}catch(Exception e){
		logger.error(e.getMessage(),e);
		logger.info("######代理商信息匹配导出Excel失败######");
	      addActionError("请先导入商户号excel！");
		return ERROR;
	}
	return SUCCESS;
}
	
	
	


	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {

		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {

		this.setSearchConditionToSubClass(searchCondition);
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {

		getSession().setAttribute(SEARCH_SESSION_BLACK_LIST_QUERY, searchCondition);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {

		return (BaseSearchCondition) getSession().getAttribute(SEARCH_SESSION_anency_LIST_QUERY);
	}

	@Override
	protected String getInitPageSize() {

		return Constance.PAGE_MAX_SIZE+"";
	}
	


	public AgencyActionSearchCondition getSearchCondition() {
		return searchCondition;
	}


	public void setSearchCondition(AgencyActionSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}


	public File getFile() {
		return file;
	}


	public void setFile(File file) {
		this.file = file;
	}
	public InputStream getExcelFile() {
		return excelFile;
	}
	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}
	public String getExcelName() {
		String excelName="代理商信息表"+Constance.formateDate();
		 
			try {
				excelName = new String(excelName.getBytes(),"ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				logger.info("生成excel名称失败了！");
			}
		 
		return  excelName;
		
	}
	public void setExcelName(String excelName) {
		this.excelName = excelName;
	}


	
}